package com.wzh.glsc.order.config;

import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * @author xiaoming
 * @PackageName:com.wzh.glsc.order.config
 * @ClassName:@{NAME}
 * @Description:
 * @date:@{DATE}@{TIME}
 */
@Configuration
public class OrderFeignConfig {

    @Bean
    public RequestInterceptor requestInterceptor(){

        return new RequestInterceptor() {
            @Override
            public void apply(RequestTemplate requestTemplate) {
                //RequestContextHolder 就spring提供的上下文信息保持器。原理是把信息放在了同步线程ThreadLocal中
                //             可以通过其提供的getRequestAttributes()拿到用户的请求信息(RequestAttributes对象)
                //              这里的ServletRequestAttributes 是(RequestAttributes对象)实现接口，可以获取到请求头信息
                ServletRequestAttributes servletRequestAttributes=(ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
                if(servletRequestAttributes!=null) {
                    //从ServletRequestAttributes 获取到用户的request
                    HttpServletRequest request = servletRequestAttributes.getRequest();
                    //取出request中请求头的cookie放入到RequestTemplate的请求头中
                    //          session信息放在cookie中
                    requestTemplate.header("Cookie", request.getHeader("Cookie"));
                }
            }
        };
    }
}
